<template>
		<div ref="fullscreenElement">
			 <Modelheader :imgarrayJk="imgarrayJk" :examStatus="examStatus"></Modelheader>
			 <div class="uploadMarks">
                 <div class="horizontalpositioning" @click="horizontalpositioning" v-if="examStatus==0">调整水平定位</div>
				 <div class="horizontalpositioning" v-else>调整水平定位</div>
				 <div class="boxcenter">
                    <span class="uploaddivattention">请上传 <i>2 张</i> 200dpi分辨率彩色图像  扫描模板图（拖动可排序）</span>
					 <div class="uploadCardimage">
						 <div class="uploaddiv">
                            <draggable :list="imgarray" :animation="100" :forceFallback="true"  @end="onEnd" @change="onMoveCallback" class="imgmove">
                                <transition-group name="fade">
                                <div v-for="(item, index) in imgarray" :key="item.pageNo" class="boxsetdelecte" v-if="imgarray.length > 0">
                                        <b>{{index+1}}</b>
                                    <img :src="item.imageUrl" alt="" style="width:200px;border: 1px solid #295cff80;">
                                    <span><img src="../../assets/images/drag.png" alt="" style="width:24px;height:24px;"></span>
                                    <div class="buttonboxedit">
                                        <i>第{{ index+1 }}页</i>
                                        <i><input type="file" class="fileIndex" @change="handleFileByIndex($event, index,item.id)" accept="image/*" />修改</i>
                                    </div>
                                </div>
                                </transition-group>
                            </draggable>
                            <!-- 第一张图片上传 -->
							 <div class="uploadlist" v-show="pageoneishow" v-loading="loading">
                                <div class="upload-image">
                                    <!-- <input type="file" class="fileIndex" multiple @change="handleFileChange" accept="image/*" /> -->
                                    <input type="file" class="fileIndex" @change="handleFileChange" accept="image/*" />
                                    <div class="uploadBoxinfo">
                                        点击上传
                                    </div>
                                </div>
                            </div>
                            <!-- 第二张图片上传 -->
							 <div class="uploadlist" v-show="pagetwoishow" v-loading="loading">
                                <div class="upload-image">
                                    <!-- <input type="file" class="fileIndex" multiple @change="handleFileChange" accept="image/*" /> -->
                                    <input type="file" class="fileIndex" @change="handleFileChange1" accept="image/*" />
                                    <div class="uploadBoxinfo">
                                        点击上传
                                    </div>
                                </div>
                            </div>
						 </div>
					 </div>
				 </div>
			 </div>
		</div>
</template>

<script>
// import ImageSelector from '../../components/school/imgcj.vue';
// import ImageSelector from '../../components/school/imagecanvas.vue'
// import vueCropper from '../../components/school/vuecropper.vue'
// import ImageSelector from '../../components/school/fabricimg.vue'  //切图
import UploadImage from '../../components/model/modelupload.vue';
import {updatamodelcase,addTemplateinfo,templateIdinfo} from '../../api/paperinfo/paperinfo.js'
// import { get, post, del, put } from '../../request/api.js' 
import draggable from 'vuedraggable';
import Modelheader from '../../components/model/modelhead.vue'
export default {
  name: 'App',
  data(){
	return{
		navbar:[
			{
				name:'模板信息及上传',
				id:0,
			},
			{
				name:'水平定位',
				id:1,
			},
			{
				name:'定位区',
				id:2,
			},
			{
				name:'准考证号区',
				id:3,
			},
			{
				name:'客观题区',
				id:4,
			},
			{
				name:'主观题区',
				id:5,
			}
		],
		tabnavindex:0,
		examclassify:'',
		examclassifylist:['条形码','涂点','手写'],
		examNumber:'',
		examNumberlist:[4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22],
		cardNumber:2,
		cardNumberlist:[2,4,6],
		cardColor:'',
		cardColorlist:['黑色','灰色','彩色'],
		examdpi:'',
		examdpilist:[150,200,300],
		images: [],
		questiontype:'',
		questionList:[
			{
				name:'定位点',
				id:1
			},
			{
				name:'文字定位',
				id:2
			}
		],
		
		selectradio:1,
		fillinWidth:0,
		fillinHeight:0,
		intervalWidth:0,
		intervalHeight:0,
		modelobj:{
		  id:0,
		  examId:0,
		  examCourseId:0,
		  examNoLength:0,
		  answerCardPages:0,
		  templateImages: []
		},
		moduleImageurl:{},
		examCourseId:'',//考试科目id
		modeldata:{
			templateId: 0,
			examCourseId: 0,
			type: 0
		},
		positioningare:{
			id: 0,
			templateId: 0,
			templateAreaType: 0,
			templateCuttingRegion:[]
		},
		modeltypequestion:'',
		modelarealist:[],
		modelarealistcavans:[],
		examInfo:{},
		examName:'',
		questioninfo:{},
		yzsubmiterro:false,
		imageslists:[],
		bcishow:false,
		isFullscreen: false, // 当前是否处于全屏状态
        imgarray:[],
        pageoneishow:true,
        pagetwoishow:true,
		loading:false,
		imgarrayJk:[],
		examStatus:0
	}  
  },
  mounted() {
	document.onfullscreenchange = this.handleFullscreenChange;
	if(sessionStorage.getItem('imgarray')){
		this.imgarray=JSON.parse(sessionStorage.getItem('imgarray'))
        this.imgarray.forEach(item => {
            if (item.pageNo === 1) {
                this.pageoneishow=false
				this.loading = false
            } else if (item.pageNo === 2) {
                this.pagetwoishow = false
				this.loading = false
            }
        });
    }else{
        //接口返回的参数
        this.modeltab()
    }
  },
  methods:{
    // 获取模板
	modeltab(){
        let obj={
            templateId:this.$route.query.templateId,
        }
        templateIdinfo(obj).then(res=>{
            if(res.code==200){
				console.info(res.data)
                this.imgarray = res.data
				this.imgarrayJk = res.data
				this.examStatus = res.data&&res.data.length!=0&&res.data[0].editStatus
                 res.data.forEach(item => {
                    if (item.pageNo === 1) {
                        this.pageoneishow=false
						this.loading = false
                    } else if (item.pageNo === 2) {
                        this.pagetwoishow = false
						this.loading = false
                    }
                });
            }
        })
	},
    //跳着调整水平定位
    horizontalpositioning(){
        if(this.imgarrayJk&&this.imgarrayJk.length==0&&this.imgarray.length==0&&!sessionStorage.getItem('imgarray')){
            this.$message.warning('请先上传模板')
         	return false
        }
		this.$router.push('/horizontalpositioning?templateId='+this.$route.query.templateId+'&examName='+this.$route.query.examName+'&examId='+this.$route.query.examId)
		// if(this.imgarrayJk&&this.imgarrayJk.length>0){
		// 	this.$router.push('/horizontalpositioning?templateId='+this.$route.query.templateId+'&examName='+this.$route.query.examName)
		// 	return false
		// }
        // addTemplateinfo(this.imgarray).then(res=>{
        //     console.info('res',res)
        //     if(res.code==200){
        //         this.$router.push('/horizontalpositioning?templateId='+this.$route.query.templateId+'&examName='+this.$route.query.examName) 
        //         sessionStorage.removeItem('imgarray')
        //     }
        // })
    },
    onEnd(event) {
		const newIndex = event.newIndex;
			  // 更新拖拽元素的 page 值
		this.imgarray.forEach((image, index) => {
		        image.pageNo = index + 1; // 更新 page 属性为新的索引值加 1
	   })
	   sessionStorage.setItem('imgarray', JSON.stringify(this.imgarray));
		// //console.info(this.imgarray)
	  },
		  onMoveCallback(list){
			  // //console.info(this.imgarray)
			  // //console.info(list)
		  },
	  modeltype(data){
		  this.modeltypequestion = data
	  },
	updateImage(newImageUrl) {
		// //console.info(newImageUrl)
		this.images = newImageUrl
	},
	imageurllist(data){
		this.images = data
	},
    // 处理第一页的上传
  handleFileChange(event) {
    this.uploadFile(event, 1,0); // 传入页码1
  },
  
  // 处理其他页的上传
  handleFileChange1(event) {
    this.uploadFile(event, 2,0); // 传入页码2或其他逻辑
  },
  //修改
  handleFileByIndex(event,index,id){
    this.uploadFile(event, index+1,id); // 传入页码2或其他逻辑
  },
  // 统一的文件上传方法
  uploadFile(event, pageNo,id) {
	this.loading = true
        const file = event.target.files[0];
        if (!file) return;

        const formData = new FormData();
        formData.append('file', file);

        updatamodelcase(formData)
        .then(res => {
            if (res.code === 200) {
                if(pageNo==1){
                    this.pageoneishow=false
					this.loading = false
                }else{
                    this.pagetwoishow=false
					this.loading = false
                }
            // 查找是否已存在相同pageNo的项
            const existingIndex = this.imgarray.findIndex(item => item.pageNo === pageNo);
            const newItem = {
                templateId: this.$route.query.templateId,
                pageNo: pageNo,
                imageUrl: res.url,
                id:id
            };

            if (existingIndex >= 0) {
                // 替换现有项
                this.$set(this.imgarray, existingIndex, newItem);
            } else {
                // 添加新项
                this.imgarray.push(newItem);
            }
            sessionStorage.setItem('imgarray', JSON.stringify(this.imgarray));
            
            // 重置文件输入，允许重复选择同一文件
            event.target.value = '';
            }
        })
        .catch(error => {
            console.error('上传失败:', error);
        });
    },
	modeluploadcancel(){
		
	},
	zdsbmodel(){},
	// 处理全屏状态变化
	handleFullscreenChange() {
	  this.isFullscreen = !document.fullscreenElement;
	}
  },
  components: {UploadImage,draggable,Modelheader},
  destroyed() {
		if(this.imgarray.length!=0){
			addTemplateinfo(this.imgarray).then(res=>{
				if(res.code==200){
					sessionStorage.removeItem('imgarray')
					// this.modeltab()
				}
			})
		}
  }
//   destroyed() {
// 	if(this.imgarray.length==0){  
// 		return false
// 	}
// 	addTemplateinfo(this.imgarray).then(res=>{
// 		console.info('res',res)
// 		if(res.code==200){
// 			sessionStorage.removeItem('imgarray')
// 		}
// 	})
//   }
//   beforeRouteLeave(to, from, next) {
// 	  if(this.bcishow){
// 		  next();
// 	  }else{
// 		  // 比较两个数组+
// 		  //console.info('111',JSON.stringify(this.imageslists.templateImages))
// 		  //console.info('222',this.images)
// 		  if (JSON.stringify(this.imageslists.templateImages) != JSON.stringify(this.images)) {
// 		  		  //console.info('dddssssss')
// 		    // 如果数组不同，阻止跳转并提示用户
// 		  		this.$confirm('有未保存的操作，是否继续', '提示', {
// 		  		  confirmButtonText: '确定',
// 		  		  cancelButtonText: '取消',
// 		  		  type: 'warning'
// 		  		}).then(() => {
// 		  			next();
// 		  		}).catch(() => {
// 		  			next(false);     
// 		  		});
// 		    next(false); // 阻止跳转
// 		  } else {
// 		    // 如果数组相同，允许跳转
// 		    next();
// 		  }
// 	  }
//     },
}
</script>

<style scoped>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  text-align: center;
  color: #2c3e50;
}

/* 上传 */
.uploadMarks{
	box-sizing: border-box;
	background:#F4F7FD;
	width:100vw;
	height:calc(100vh - 102px);
	position: relative;
    background:#F4F7FD;
}
.smcsbutton{
	width: 124px;
	height: 34px;
	background: #1A48DB;
	border-radius: 10px;
	font-size: 14px;
	color: #FFFFFF;
	text-align: center;
	border:none;
	/* margin:24px 0 0 24px; */
	position: absolute;
	padding:0;
	left:24px;
	top:24px;
}
.uploadcardInfo{
	height:calc(100vh - 102px);
	background:#fff;
	position:relative
}
.examboxbutton{
	width:100%;
	box-sizing: border-box;
	display: flex;
	align-items: center;
	padding:0 15px;
	height: 54px;
	background: #E8F0FA;
	position:absolute;
	left:0;
	bottom:0;
}
.examboxbutton >>>  .el-button{
	width: 124px;
	height: 34px;
	border-radius:10px;
	padding:0;
	margin:0;
	font-size:12px;
	border: 1px solid #295CFF;
	color:#295CFF;
	background:none;
}
.examboxbutton >>>  .el-button:first-child{
	background:#295CFF;
	border: 1px solid #295CFF;
	color:#fff;
}
.examboxbutton >>>  .el-button:nth-child(2){
	margin:0 8px;
}
.examboxbutton1{
	width:100%;
	box-sizing: border-box;
	display: flex;
	align-items: center;
	padding:0 15px;
	height: 54px;
	background: #E8F0FA;
	position:absolute;
	left:0;
	bottom:0;
	justify-content: center;
}
.examboxbutton1 >>>  .el-button{
	width: 124px;
	height: 34px;
	border-radius:10px;
	padding:0;
	margin:0;
	font-size:12px;
	border: 1px solid #295CFF;
	color:#295CFF;
	background:none;
}
.examboxbutton1 >>>  .el-button:first-child{
	background:#295CFF;
	border: 1px solid #295CFF;
	color:#fff;
}
.examboxbutton1 >>>  .el-button:nth-child(2){
	margin:0 8px;
}
.uploadcardInfo h3{
	line-height:67px;
	border-bottom:solid 1px #D8E4F0;
	padding:0 24px;
	color:#2A303B;
	font-weight:normal
}
.uploadcardInfo ul li{
	display: flex;
	align-items: center;
	color:#8E96A4;
	font-size:16px;
	padding:0 24px;
	margin-top:24px;
}
.uploadcardInfo ul li span{
	color:#8E96A4;
	width:100px;
}
.uploadcardInfo ul li >>> .el-input__inner{
	border-radius:10px;
}
.uploadcardInfo ul li >>> .el-textarea{
	width:calc(100% - 100px)
}
.uploaddiv{
	display: flex;
	flex-wrap: wrap;
	justify-content: center;
}
.uploaddivattention{
    display: block;
    width:100%;
	font-size: 18px;
	color: #B3B8C2;
    text-align: center;
    padding-top:24px;
}
.uploaddivattention i{
    font-style:normal;
    color:#1A48DB
}
.cropperBox{
	height:calc(100vh - 102px);
	display: flex;
}
.cropperImageset{
	width:calc(100% - 370px);
	height:calc(100vh - 102px);
	overflow:scroll;
	position: relative
}
.routate{
  	position:absolute;
  	left:50px;
  	top:5px;
  	background:#fff;
  	height:60px;
  	display: flex;
  	align-items: center;
  	padding:0 10px 0 0;
  	box-shadow: 0 0 5px rgba(0,0,0,0.1);
  	border-radius:5px;
  	font-size:14px;
  	color:#557292;
  	border-radius: 10px;
	z-index:10
  }
 .routate >>> .el-select,.routate >>>.el-input{
  	width:150px;
  }
 .routate >>> .el-select{
  	margin-right:10px;
  }
  .routate >>>.el-input{
  	margin-left:10px;
  	margin-right:10px;
  }
 .routate >>> .el-button{
  	border-radius:10px;
  	height:35px;
  	width:55px;
  	padding:0 ;
	margin-left:10px
  }
  .routate >>> .el-input__inner{
  	border-radius:10px;
  	height:35px;
  }
  .image-preview img{
	  box-sizing: border-box;
	  width: 150px;
	  height: 150px;
	  background: #FFFFFF;
	  border-radius: 10px;
	  text-align: center;
	  font-size:16px;
	  color:#295CFF;
	  cursor: pointer;
	  margin:22px;
  }
  
  .breadBox >>> .el-breadcrumb__inner a,.breadBox >>> .el-breadcrumb__inner.is-link{
  	font-weight:normal
  }
  .breadBox >>> .el-breadcrumb__item:last-child .el-breadcrumb__inner,
  .breadBox >>> .el-breadcrumb__item:last-child .el-breadcrumb__inner a,
  .breadBox >>> .el-breadcrumb__item:last-child .el-breadcrumb__inner a:hover,
  .breadBox >>> .el-breadcrumb__item:last-child .el-breadcrumb__inner:hover{
  	font-weight:bold
  }
  
  .uploadCardimage{
    width:100%;
    position: absolute;
    left:0;
    top:50%;
    transform: translateY(-50%);
  }
  .imgmove span{
	display: flex;
	align-items: center;
	margin:0 13px;
}
.imgmove span div{
	margin:0 13px;
}
.boxsetdelecte{
	position:relative;
}
.boxsetdelecte span{
	position:absolute;
	left:-24px;
	top:24px;
}
.buttonboxedit{
	display: flex;
	align-items: center;
	justify-content: center;
	padding-top:5px;
}
.buttonboxedit i{
	width: 52px;
	height: 24px;
	border-radius: 12px;
	font-size: 12px;
	color: #295CFF;
	text-align: justify;
	line-height:24px;
	text-align: center;
	font-style:normal;
	cursor: pointer;
}
.buttonboxedit i:last-child{
	background: #ec555a1a;
	color:#EC555A;
	margin-left:15px;
}
.boxsetdelecte b{
	display: block;
	text-align: center;
	font-size:20px;
	padding-bottom:6px;
}
.uploadlist{
		display: flex;
		align-items: center;
        margin:0 20px;
	}
.upload-image {
  display: flex;
  flex-direction: column;
  align-items: center;
  position:relative;
  width:200px;
  height:140px;
  margin:22px 0;
}
.uploadBoxinfo{
	box-sizing: border-box;
	width: 200px;
	height: 140px;
	background: #FFFFFF;
	border-radius: 10px;
	border: 1px dashed #D8E4F0;
	text-align: center;
	font-size:18px;
	color:#295CFF;
	cursor: pointer;
	position:absolute;
	z-index:1;
    line-height:140px;
}
.uploadBoxinfo i{
	display:block;
	color:#D8E4F0;
	padding:5px 0;
}
.fileIndex{
	position:absolute;
	left:0;
	top:0;
	width:100%;
	height:100%;
	z-index:2;
	cursor: pointer;
	opacity: 0;
}
.horizontalpositioning{
    position:absolute;
    left:24px;
    bottom:24px;
    background:#1A48DB;
    text-align: center;
    line-height:32px;
    border-radius:4px;
    padding:0 10px;
    color:#fff;
    cursor: pointer;
    font-size:14px;
}
</style>